<template>
	<view class="content">
		<ZPaging
		    ref="paging"
		    v-model="list"
			:auto="false"
		    :auto-show-system-loading="true"
			loading-more-no-more-text="沒有更多了"
			loading-more-default-text="點擊加載更多"
			loading-more-loading-text="正在加載..."
			loading-more-fail-text="加載失敗,點擊重新加載"
			empty-view-text="沒有數據哦~"
			refresher-default-text="繼續下拉刷新"
			refresher-pulling-text="鬆開立即刷新"
			refresher-refreshing-text="正在刷新"  
			empty-view-reload-text="重新加載"
			empty-view-error-text="加載失敗"
		    @query="queryList"
		>
		     <template #top>
		        <NavBar :title="title" :autoBack="false" id="nav">
		        	<template #left>
		        		<view class="navbar-left center" @click="goBack">
		        			<u-icon name="arrow-left" color="#007aff" size="34"></u-icon>
		        			<text class="c007aff">{{lefttitle}}</text>
		        		</view>
		        	</template>
		        	<template #right>
		        		<view class="navbar-right center" @click="showLists">
		        			<u-icon class="ml-20" name="list-dot" color="#007aff" size="34"></u-icon>
		        		</view>
		        	</template>
		        </NavBar>
				<view class="navlist" :class="navshow?'navshow':''">
					<view class="f26 item" v-for="(v,k) in sortList" :key="k" @click="selectSort(k)">
						<u-icon name="checkmark" :color="curIndex==k?'#007aff':'#fff'"></u-icon>
						<text class="ml-10 f26">{{v.name}}</text>
					</view>
					<view class="f26 mt-10 start item upload" @click="upFiles">
						<u-image class="mt-6" src="../../static/upload-fill.png" width="28rpx" height="28rpx" mode="aspectFill"></u-image> 
						<text class="c007aff ml-10 f26">上傳</text>
					</view>
					
				</view>
		    </template>
		    <template #default>
				
				<view class="widths start list">
					
					<view class="center dirCloumn item" v-for="(v,k) in list" :key="k" @longpress="delFile(v.path,v.type,v.filename)" @click="openFile(v.path,v.type,v.filename)">
						
						<view class="pic">
							<u-image v-if="v.type=='png' || v.type=='jpg' || v.type=='jpeg' || v.type=='bmp' || v.type=='gif' " :src="v.path" width="128rpx" height="128rpx" mode="aspectFill"></u-image> 
							<u-image v-else-if="v.type=='xls' || v.type=='xlsx'" src="../../static/excel.png" width="128rpx" height="128rpx" mode="aspectFill"></u-image> 
							<u-image v-else-if="v.type=='doc' || v.type=='docx'" src="../../static/word.png" width="128rpx" height="128rpx" mode="aspectFill"></u-image> 
							<u-image v-else-if="v.type=='ppt' || v.type=='pptx'" src="../../static/ppt.png" width="128rpx" height="128rpx" mode="aspectFill"></u-image> 
							<u-image v-else-if="v.type=='pdf'" src="../../static/pdf.png" width="128rpx" height="128rpx" mode="aspectFill"></u-image> 
							<u-image v-else-if="v.type=='rar' || v.type=='zip' || v.type=='gz' || v.type=='bz2' || v.type=='7z'" src="../../static/zip.png" width="128rpx" height="128rpx" mode="aspectFill"></u-image> 
							<u-image v-else src="../../static/other.png" width="128rpx" height="128rpx" mode="aspectFill"></u-image> 
						</view>
						<view class="info">
							<view class="text-cut c333 title">{{v.filename}}</view>
							<view class="center c666 f24 time">{{v.time}}</view>
							<view class="center c666 f24 size">{{v.size}}</view>
						</view>
					</view>
					
					
				</view>
		        
		
		    </template>
		 </ZPaging>
		
		<Tabar></Tabar>
		<u-modal v-model="delshow" :show-cancel-button="true" content="確認刪除該文件嗎？" @confirm="confirmDelFile"></u-modal>
		
	</view>
</template>

<script>
	import {downLoadFile } from "@/utils/util/uploadFun.js"
	import {isWxBrowser, isIos } from "@/utils/util/index.js"
	import { mapState, mapMutations } from "vuex";
	import Tabar from "@/component/HomeTab"
	import NavBar from "@/component/NavBar"
	import { baseUrl } from "@/api/url.js"
	import { getFileList , delFiles } from "@/api/apis.js"
	import ZPaging from "@/node_modules/z-paging/components/z-paging/z-paging.vue"
	import { indexOf } from "lodash";
	var passwordRegex = /^[a-zA-Z0-9_]{6,16}$/;
	export default {
		components:{
			Tabar,
			ZPaging,
			NavBar
		},
		data() {
			return {
				delFilePath:"",
				delshow:false,
				isIos:null,
				isWx:null,
				action: baseUrl+'/api/apict/uploadfiles',
				showUpload:false,
				isPc:null,
				title:"",
				lefttitle:"",
				curId:0,
				name:"",
				path:"",
				list:[],
				navshow:false,
				sortList:[
					{
						id:1,
						name:'名稱',
					},
					{
						id:2,
						name:'大小',
					},
					{
						id:3,
						name:'日期',
					}
				],
				curIndex:0,
				sort:"desc",
				fileType:{
					'files':['.xlsx,.xls,.doc,.docx,.rtf,.ppt,.pptx,.pdf,.png,.jpg,.jpeg,.gif'],
					'img':['.pdf,.png,.jpg,.jpeg,.gif,.bmp'],
					'zip':['.zip,.rar,.rar4,.7z,.tar,.gz,.bz2,.xz']
				}
				
			}
		},
		onShow(){
			
			this.isIos=isIos()
			this.isWx=isWxBrowser()
			this.$nextTick(()=>{
				if(uni.getStorageSync("islogin")){
					const { id,tit,name,path } = this.$Route.query
					if(id){
						this.curId=id
						this.name=name
						this.path=path
						this.title=name
						this.lefttitle=tit
					}else{
						let f = uni.getStorageSync("fileDir")
						if(f){
							this.curId=f.caseid
							this.name=f.tit
							this.path=f.type
							this.title=f.tit
							this.lefttitle=f.lefttit
							this.reload()
						}else{
							this.$Toast("數據錯誤")
							setTimeout(()=>{
								this.toPage("Main")
							},1200)
						}
					}
					if(!this.curId){
						this.$Toast("數據錯誤")
						setTimeout(()=>{
							this.toPage("Main")
						},1200)
					}else{
						this.reload()
					}
				}else{
					this.$Toast("請先登錄")
					setTimeout(()=>{
						this.toPage("Home")
					},1200)
				}
			})
		},
		onLoad() {
		},
		computed: {
			...mapState(["userinfo","fileAction"]),
		},
		methods: {
			...mapMutations(['changeFileAction','chageUserPageType','chageUserPageId','changeUserIdent','changeUserName']),
			queryList(pageNo,pageSize){
				let uid = uni.getStorageSync("uid")
				let data = {
					pageNo,
					pageSize:18,
					uid,
					path:this.path,
					caseid:this.curId,
					type:this.sortList[this.curIndex].id,
					sort:this.sort
				}
				getFileList(data).then((res)=>{
					this.$refs.paging.complete(res)
				}).catch((err)=>{
					if(err.code === 102){
						this.$ClearLogin(err.msg)
					}else{
						this.$Toast(err.msg)
					}
				})
				
			},
			selectSort(i){
				this.curIndex=i
				this.navshow=false
				if(this.sort=='desc'){
					this.sort='asc'
				}else{
					this.sort='desc'
				}
				this.reload()
			},
			delFile(path,type,title){
				this.delshow=true
				this.delFilePath=path.replace(baseUrl,'')
			},
			confirmDelFile(){
				this.delshow=false
				let uid = uni.getStorageSync("uid")
				let data={
					uid,
					file:this.delFilePath
				}
				delFiles(data).then((res)=>{
					this.$Toast(res.msg)
					setTimeout(()=>{
						this.reload()
					},1200)
				}).catch((err)=>{
					if(err.code==102){
						this.$ClearLogin('登录已过期')
					}else{
						this.$Toast(data.msg)
					}
				})
			},
			openFile(path,type,title){
				let arr = ['png','jpg','jpeg','gif','bmp']
				if(indexOf(arr,type) != -1){
					uni.previewImage({
						current:0,
						urls: [path],
						indicator:'number',
						longPressActions: {
							// itemList: ['发送给朋友', '保存图片', '收藏'],
							// success: function(data) {
							// 	console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
							// },
							// fail: function(err) {
							// 	console.log(err.errMsg);
							// }
						}
					});
				}else{
					// this.toPage("FileList",{path,title})
					let f={
						caseid:this.curId,
						type:this.path,
						lefttit:this.lefttitle,
						tit:this.name,
					}
					uni.setStorageSync("fileDir",f)
					this.changeFileAction(f)
					if(this.isWx){
						//跳轉頁面
						// this.toPage('FileList',{path,title})
						uni.navigateTo({
							url:"/pages/index/filelist?path="+encodeURIComponent(path)+"&title="+encodeURIComponent(title)
						})
					}else{
						downLoadFile(path)
					}
					
				}
				
			},
			reload(){
				this.$refs.paging.reload()
			},
			showLists(){
				this.navshow=!this.navshow
			},
			
			upFiles(){
				this.navshow=false
				// this.showUpload=true
				let allow="";
				if(this.path=='files'){
					allow=this.fileType.files
				}else if(this.path=='img'){
					allow=this.fileType.img
				}else{
					allow=this.fileType.zip
				}
				
				// success: (chooseImageRes) => {
				// 	const tempFilePaths = chooseImageRes.tempFilePaths;
				// 	this.$Loading("上传中")
				// 	let uploadedCount = 0;
				// 	tempFilePaths.forEach((item)=>{
				// 		uni.uploadFile({
				// 			header:{
				// 				'token':uni.getStorageSync('userToken')
				// 			},
				// 			url: this.action, //仅为示例，非真实的接口地址
				// 			filePath: item,
				// 			name: 'file',
				// 			success: (uploadFileRes) => {
				// 				let data = JSON.parse(uploadFileRes.data);
				// 				uploadedCount++; 
				// 				// this.$Toast(data.msg)
				// 				if(data.data.code===1){
				// 					// this.info.pic = data.data.url
				// 					this.info.pic.push(data.data.url)
				// 				}else{
				// 					this.$Toast(data.msg)
				// 				}
				// 			},
				// 			fail:(err)=>{
				// 				let errMsg = JSON.parse(err.data)
				// 				this.$Toast(errMsg.msg)
				// 			},
				// 			complete: () => {
							
				// 			  if (uploadedCount === tempFilePaths.length) { 
				// 				this.$Toast("上传成功")
				// 			  }else{
				// 				  this.$Toast("部分上传成功")
				// 			  }
				// 			}
				// 		});
				// 	})
					
				// }
				
				
				uni.chooseFile({
					count:9,
					extension:allow,
					success: (res) => {
						let tempFilePaths = res.tempFilePaths;
						let uid = uni.getStorageSync("uid")
						let data={
							type:this.path,
							caseid:this.curId,
							uid:uni.getStorageSync("uid"),
						}
						let uploadedCount=0;
						this.$Loading("上传中")
						tempFilePaths.forEach((item,key)=>{
							uni.uploadFile({
								header:{
									'token':uni.getStorageSync('userToken')
								},
								url: this.action, //仅为示例，非真实的接口地址
								filePath: item,
								name: 'file',
								formData:data,
								success: (uploadFileRes) => {
									
									let data = JSON.parse(uploadFileRes.data);
									if(data.code===1){
										this.$Toast(data.msg)
										this.reload();
									}else{
										if(data.code==101 || data.code==102){
											this.$ClearLogin('登录已过期')
										}else{
											this.$Toast(data.msg)
										}
										
									}
								},
								fail:(err)=>{
									let errMsg = JSON.parse(err.data)
									this.$Toast(errMsg.msg)
								},
								complete: () => {
								
								 //  if (uploadedCount === tempFilePaths.length) { 
									// uni.hideLoading()
									// this.$Toast("上传成功")
								 //  }else{
									// this.$Toast("部分上传成功")
								 //  }
								 if(key==(tempFilePaths.length-1)){
									 uni.hideLoading()
									 this.$Toast("上传成功")
								 }
								}
							});
						})
					}
				});
			},
			toPage(name,params={}){
				this.$navi({
				    route:{
				        name,
						params
				    },
				})
			},
			goBack(){
				// uni.navigateBack(-1)
				this.toPage('Casedata',{id:this.curId})
			},
		}
	}
</script>

<style lang="scss">
	page{
		background-color: #f1f1f1;
		
	}
	.content{
		min-height: 100vh;
	}
	.navlist{
		position: fixed;
		top:88rpx;
		right: 0px;
		background-color: #fff;
		width: 200rpx;
		z-index: 99999;
		height: 0px;
		overflow: hidden;
		&.navshow{
			height: 224rpx;
			box-shadow: -2rpx 2rpx 8rpx rgba(0,0,0,.15);
			border-radius: 0 0 0 8rpx;
		}
		.item{
			line-height: 2;
			padding: 0rpx 20rpx;
			&:last-child{
				padding-bottom: 8rpx;
			}
			&.upload{
				border-top: 2rpx solid #ccc;
				margin-top: 10rpx;
			}
		}
	}
	.list{
		background-color: #f1f1f1;
		padding-top: 108rpx;
	    display: grid;
		justify-content: space-evenly;
		grid-template-columns: repeat(auto-fill, 200rpx);
		grid-gap: 10px;
		.item{
			// width: 200rpx;
			// margin: 20rpx;
			overflow: hidden;
			height: 268rpx;
			.pic{
				height: 128rpx;
			}
			.info{
				width: 100%;
				.title{
					word-break: break-all;
					text-align: center;
				}
				.time,.size{
					width: 100%;
					text-align: center;
				}
			}
		}
	}
</style>
